<?php

class FieldController extends \BaseController {

    /**
	 * Controller constructor
	 */
	public function __construct() {
		$this->beforeFilter('auth', array('except' => array('getAPI', 'storeAPI', 'updateAPI', 'destroyAPI')));
	}
	
	/**
	 * Display a listing of fields.
	 *
	 * @return Response
	 */
	public function index()
	{
		// get all the match types
		$matchTypes = MatchType::all();
		// get all the matches
		$fields = Field::all();
		
		foreach($fields as $item){
			$item->totalMatches = $item->matches->count();
			
			$matchesId = array();
			foreach ($item->matches as $key => $match){
				$matchesId[$key] = $match->id;
			}
			if(sizeof($matchesId) > 0){
				$item->playedMatches = Match::whereIn('id', $matchesId)
												->where(
													DB::raw('(select count(*) from match_teams mt
														        inner join team t on mt.teamId = t.id
														        inner join team_users tu on tu.teamId = t.id
														        inner join user u on u.id = tu.userId
														    where  mt.matchId = match_data.id)'), 
													'>=', 
													DB::raw('(select totalPlayers from match_type mty where mty.id = match_data.matchTypeId)')
												)
												->count();
			} else {
				$item->playedMatches = 0;
			}
		}

		// load the view and pass the matches
		return View::make('fields.index')
			->with('fields', $fields)
			->with('matchTypes', $matchTypes);
	}


	/**
	 * Show the form for creating a new field.
	 *
	 * @return Response
	 */
	public function create()
	{
		// get all the match types
		$matchTypes = MatchType::all();
		return View::make('fields.create')
			->with('matchTypes', $matchTypes);
	}


	/**
	 * Store a newly created field in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		// validate
		$rules = array(
			'name'       => 'required',
			'price'      => array('regex:/^\d+(\.\d{1,2})?$/')
		);
		$validator = Validator::make(Input::all(), $rules);

		// process the login
		if ($validator->fails()) {
			return Redirect::to('fields/create')
				->withErrors($validator)
				->withInput(Input::except('password'));
		} else {
			// store
			$field = new Field();
			$field->name       = Input::get('name');
			$field->address       = Input::get('address');
			$field->town       = Input::get('town');
			$field->state       = Input::get('state');
			$field->country       = Input::get('country');
			$field->contact       = Input::get('contact');
			$field->latitude       = Input::get('latitude');
			$field->longitude       = Input::get('longitude');
			$field->price       = Input::get('price') != null && Input::get('price') != "" ? Input::get('price') : 0;
			$field->uploaded_by_user = 0;
			$field->save();
			
			// store related Match Types
			$matchTypeIds = Input::get('matchTypes');
			if(is_array($matchTypeIds))
			{
				$field->types()->sync($matchTypeIds);
			}
			
			// redirect
			Session::flash('message', 'Cancha creada!');
			return Redirect::to('fields');
		}
	}


	/**
	 * Display the specified field.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		// get the field
		$field = Field::find($id);

		// get the amount of games played by match type 
		$statistics = array();
		foreach($field->matches as $key=>$value){
			$matchTypeName = $value->type->name;
			
			if(array_key_exists($matchTypeName, $statistics))
				$statistics[$matchTypeName] += 1;
			else
				$statistics[$matchTypeName] = 1;
		}
		
		// show the edit form and pass the field
		return View::make('fields.show')
			->with('field', $field)
			->with('statistics', $statistics);
	}


	/**
	 * Show the form for editing the specified field.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		// get all the match types
		$matchTypes = MatchType::all();
		// get the field
		$field = Field::find($id);

		// show the edit form and pass the field
		return View::make('fields.edit')
			->with('field', $field)
			->with('matchTypes', $matchTypes);
	}


	/**
	 * Update the specified field in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		// validate
		$rules = array(
			'name'       => 'required',
			'price'      => array('regex:/^\d+(\.\d{1,2})?$/')
		);
		$validator = Validator::make(Input::all(), $rules);
		
		// process the login
		if ($validator->fails()) {
			return Redirect::to('fields/' . $id . '/edit')
				->withErrors($validator)
				->withInput(Input::except('password'));
		} else {
			// store
			$field = Field::find($id);
			$field->name       = Input::get('name');
			$field->address       = Input::get('address');
			$field->town       = Input::get('town');
			$field->state       = Input::get('state');
			$field->country       = Input::get('country');
			$field->contact       = Input::get('contact');
			$field->latitude       = Input::get('latitude');
			$field->longitude       = Input::get('longitude');
			$field->price       = Input::get('price');
			$field->uploaded_by_user = Input::get('uploaded_by_user') != null ? Input::get('uploaded_by_user') : 0;
			$field->save();
			
			// store related Match Types
			$matchTypeIds = Input::get('matchTypes');
			if(is_array($matchTypeIds))
			{
				$field->types()->sync($matchTypeIds);
			}
			
			// redirect
			Session::flash('message', 'Cancha actualizada!');
			return Redirect::to('fields');
		}
	}


	/**
	 * Remove the specified field from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		// delete
		$field = Field::find($id);
		$field->delete();

		// redirect
		Session::flash('message', 'Cancha eliminada!');
		return Redirect::to('fields');
	}
	
	/*
	 * API Methods
	 */
	/**
	 * Display a listing of fields in JSON format.
	 *
	 * @return JSON Response
	 */
	public function getAPI($id = null)
	{
		if (is_null($id))
			return Response::json(Field::all());
		else
		{
			$field = Field::find($id);
			if(is_null($field)){
				return Response::json('Field not found', 404);
			} else {
				return Response::json($field);
			}
		}
	}
	
	/**
	 * Store a newly created field in storage from JSON posted data.
	 *
	 * @return JSON Response
	 */
	public function storeAPI()
	{
		$newField = Input::json();
	
		$field = new Field();
		$field->name = $newField->get('name');
		$field->address = $newField->get('address');
		$field->town = $newField->get('town');
		$field->state = $newField->get('state');
		$field->country = $newField->get('country');
		$field->contact = $newField->get('contact');
		$field->price = $newField->get('price') == "" ? 0 : $newField->get('price');
		$field->save();
	
		return Response::json($field);
	}
	
	/**
	 * Update the specified field in storage from JSON put data.
	 *
	 * @return JSON Response
	 */
	public function updateAPI()
	{
		$updateField = Input::json();
	
		$field = Field::find($updateField->get('id'));
		if(is_null($field)){
			return Response::json('Field not found', 404);
		}
		$field->name = $updateField->get('name');
		$field->address = $updateField->get('address');
		$field->town = $updateField->get('town');
		$field->state = $updateField->get('state');
		$field->country = $updateField->get('country');
		$field->contact = $updateField->get('contact');
		$field->price = $updateField->get('price') == "" ? 0 : $updateField->get('price');
		$field->save();
	
		return Response::json($field);
	}
	
	/**
	 * Remove the specified field from storage by posted id.
	 *
	 * @return JSON Response
	 */
	public function destroyAPI($id)
	{
		$field = Field::find($id);
	
		if(is_null($field))
		{
			return Response::json('Field not found', 404);
		}
		$deletedField = $field;
		$field->delete();
		return Response::json($deletedField);
	}
	

}
